import { PackageVolumeDTO, ClassVolumeDTO, UnitFileStatisticsDTO } from '../services/statistics';

// 树形节点接口
export interface TreeNode {
  name: string;
  fullPath?: string;
  value: number;
  children?: TreeNode[];
  isPackage?: boolean;
  isFile?: boolean;
  // 扩展属性
  fileCount?: number;
  codeLines?: number;
  commentLines?: number;
  blankLines?: number;
  language?: string;
  filePath?: string;
}

// 文件信息接口
export interface FileInfo {
  name: string;
  lines: number;
  fullPath: string;
}

// 包信息接口（用于旧格式兼容）
export interface PackageInfo {
  name: string;
  lines: number;
  files: FileInfo[];
}

/**
 * 将包维度体量数据和类维度体量数据转换为树形结构
 */
export function transformVolumeDataToTree(
  packageData: PackageVolumeDTO[], 
  classData: ClassVolumeDTO[]
): TreeNode[] {
  // 构建包层级映射
  const packageMap = new Map<string, PackageVolumeDTO>();
  packageData.forEach(pkg => {
    packageMap.set(pkg.packageName, pkg);
  });

  // 按包名分组文件数据
  const filesByPackage = new Map<string, ClassVolumeDTO[]>();
  classData.forEach(cls => {
    const packageName = cls.packageName;
    if (!filesByPackage.has(packageName)) {
      filesByPackage.set(packageName, []);
    }
    filesByPackage.get(packageName)!.push(cls);
  });

  // 构建树形结构
  const root: TreeNode = { name: 'root', children: [], value: 0 };
  
  // 处理每个包
  packageData.forEach(pkg => {
    const parts = pkg.packageName.split('.');
    let current: TreeNode = root;
    
    // 构建包层级结构
    for (let i = 0; i < parts.length; i++) {
      const part = parts[i];
      const fullPath = parts.slice(0, i + 1).join('.');
      
      let existing = current.children?.find(child => child.name === part);
      if (!existing) {
        existing = {
          name: part,
          fullPath,
          children: [],
          value: 0,
          isPackage: true,
          fileCount: 0,
          codeLines: 0,
          commentLines: 0,
          blankLines: 0
        };
        if (!current.children) {
          current.children = [];
        }
        current.children.push(existing);
      }
      current = existing;
    }
    
    // 为最终包节点设置统计信息
    current.value = pkg.totalLines;
    current.fileCount = pkg.fileCount;
    current.codeLines = pkg.codeLines;
    current.commentLines = pkg.commentLines;
    current.blankLines = pkg.blankLines;
    
    // 添加该包下的文件作为叶子节点
    const filesInPackage = filesByPackage.get(pkg.packageName) || [];
    current.children = filesInPackage.map(file => ({
      name: file.className + (file.filePath.endsWith('.java') ? '.java' : ''),
      fullPath: file.filePath,
      value: file.totalLines,
      isFile: true,
      codeLines: file.codeLines,
      commentLines: file.commentLines,
      blankLines: file.blankLines,
      language: file.language,
      filePath: file.filePath
    }));
  });
  
  // 递归计算每个节点的总价值
  const calculateValues = (node: TreeNode): number => {
    if (node.children && node.children.length > 0) {
      node.value = node.children.reduce((sum, child) => sum + calculateValues(child), 0);
    }
    return node.value || 0;
  };
  
  calculateValues(root);
  return root.children || [];
}

/**
 * 将类维度数据转换为Top文件列表
 */
export function transformToTopFilesList(
  classData: ClassVolumeDTO[], 
  limit: number = 10
): Array<{
  key: string;
  rank: number;
  fileName: string;
  packageName: string;
  fullName: string;
  lines: number;
}> {
  return classData
    .sort((a, b) => b.totalLines - a.totalLines)
    .slice(0, limit)
    .map((file, index) => ({
      key: file.filePath,
      rank: index + 1,
      fileName: file.className + (file.filePath.endsWith('.java') ? '.java' : ''),
      packageName: file.packageName,
      fullName: file.filePath,
      lines: file.totalLines
    }));
}

/**
 * 基于文件数据生成模拟方法数据
 * 注意：这是临时方案，实际应该从后端获取方法级别数据
 */
export function generateMockMethodsFromFiles(
  fileData: Array<{ fileName: string; fullName: string; lines: number }>,
  limit: number = 10
): Array<{
  key: string;
  rank: number;
  methodName: string;
  fileName: string;
  fullName: string;
  lines: number;
}> {
  const methods: Array<{
    key: string;
    methodName: string;
    fileName: string;
    fullName: string;
    lines: number;
  }> = [];

  fileData.forEach(file => {
    // 根据文件大小估算方法数量
    const mockMethodCount = Math.max(2, Math.min(6, Math.floor(file.lines / 200)));
    
    for (let i = 1; i <= mockMethodCount; i++) {
      const base = Math.max(20, Math.floor(file.lines / (mockMethodCount + 1)));
      const jitter = Math.floor((i * 7 + file.lines) % 80);
      const lines = base + jitter;
      const methodName = `method${i}`;
      
      methods.push({
        key: `${file.fullName}#${methodName}`,
        methodName,
        fileName: file.fileName,
        fullName: `${file.fullName}#${methodName}`,
        lines
      });
    }
  });

  return methods
    .sort((a, b) => b.lines - a.lines)
    .slice(0, limit)
    .map((item, index) => ({ ...item, rank: index + 1 }));
}

/**
 * 将后端数据转换为旧MOCK格式（用于兼容现有可视化组件）
 */
export function transformToLegacyFormat(
  packageData: PackageVolumeDTO[],
  classData: ClassVolumeDTO[]
): { packages: PackageInfo[] } {
  // 按包名分组文件数据
  const filesByPackage = new Map<string, ClassVolumeDTO[]>();
  classData.forEach(cls => {
    const packageName = cls.packageName;
    if (!filesByPackage.has(packageName)) {
      filesByPackage.set(packageName, []);
    }
    filesByPackage.get(packageName)!.push(cls);
  });

  const packages: PackageInfo[] = packageData.map(pkg => ({
    name: pkg.packageName,
    lines: pkg.totalLines,
    files: (filesByPackage.get(pkg.packageName) || []).map(cls => ({
      name: cls.className + (cls.filePath.endsWith('.java') ? '.java' : ''),
      lines: cls.totalLines,
      fullPath: cls.filePath
    }))
  }));

  return { packages };
}

/**
 * 将全量文件统计数据转换为旧MOCK格式（用于兼容现有可视化组件）
 */
export function transformFullDataToLegacyFormat(
  packageData: PackageVolumeDTO[],
  fileData: UnitFileStatisticsDTO[]
): { packages: PackageInfo[] } {
  // 按包名分组文件数据
  const filesByPackage = new Map<string, UnitFileStatisticsDTO[]>();
  
  fileData.forEach(file => {
    // 从文件路径提取包名
    const packageName = extractPackageNameFromPath(file.filePath) || 'default';
    
    if (!filesByPackage.has(packageName)) {
      filesByPackage.set(packageName, []);
    }
    filesByPackage.get(packageName)!.push(file);
  });

  const packages: PackageInfo[] = packageData.map(pkg => ({
    name: pkg.packageName,
    lines: pkg.totalLines,
    files: (filesByPackage.get(pkg.packageName) || []).map(file => ({
      name: file.fileName,
      lines: file.totalLines,
      fullPath: file.filePath
    }))
  }));

  return { packages };
}

/**
 * 从文件路径提取包名
 */
function extractPackageNameFromPath(filePath: string): string | null {
  if (!filePath || !filePath.includes('/')) {
    return null;
  }

  // 查找src/main/java或src/main/kotlin等目录
  const srcIndex = filePath.indexOf('src/main/');
  if (srcIndex === -1) {
    return null;
  }

  // 获取src/main/后面的路径部分
  const relativePath = filePath.substring(srcIndex + 10); // "src/main/" 长度为10

  // 移除文件扩展名，只保留目录路径
  const lastSlashIndex = relativePath.lastIndexOf('/');
  if (lastSlashIndex === -1) {
    return null;
  }

  const packagePath = relativePath.substring(0, lastSlashIndex);
  // 将路径分隔符转换为包名分隔符
  return packagePath.replace(/\//g, '.');
}